import { baseUrl } from '@/api/common/api.js'
const baseUrls = baseUrl


const Getajax = option => {
	return new Promise(function(reslove, reject) {
		var data = option.data || {}
		if(data.token == undefined){
			data.token = uni.getStorageSync('token');
		}
		uni.request({
			url: baseUrls + option.url,
			method: option.type || 'GET',
			data: data,
			//设置请求头，传递formdata
			// header:{
			// 	'content-type':'application/x-www-form-urlencoded; charset=UTF-8'//重点
			//     },
			header: {
				'Content-Type': 'application/x-www-form-urlencoded'
			},
			success: (res) => {
				console.log(res);
				reslove(res.data);
				if(res.data.code ==401){
					var userinfo = uni.getStorageSync('userinfo');
					var token = uni.getStorageSync("token");
					console.log(token)
					//var token = uni.getStorageSync("tokens")
					if(token == ''){
						uni.showModal({
							content:'请先注册登录',
							cancelColor:"#808080",
							success: (res) => {
								if(res.confirm){
									uni.redirectTo({
										url:'../login/login'
									});
								}else{
									console.log("取消登录操作")
								}
							}
						})
					}
				}
			},
			fail: (err) => {
				uni.showToast({
					title: '请求接口失败'
				})
				reject(err)
			},
		})
	})
};
const uploadImg = async (count, isup, stypearr, sizeTypearr) => {
	var that = this;
	let urlList = [];
	let imgList = await reqImg(count, stypearr, sizeTypearr);
	if (!isup || isup == 1) {
		for (var i = 0, len = imgList.length; i < len; i++) {
			urlList.push(await addimg(imgList[i]));
		}
		return urlList;
	} else if (isup == 2) {
		return imgList;
	}

};
//打开相册
const reqImg = (count, stypearr, sizeTypearr) => {
	var that = this;
	return new Promise((resolve, reject) => {
		let sourceType = ['album', 'camera'];
		let sizeType = ['compressed']
		//先设置默认值 打开相册选择,上传写在异步执行 执行完成后返回上传后路径
		uni.chooseImage({
			sourceType: stypearr ? stypearr : sourceType,
			sizeType: sizeTypearr ? sizeTypearr : sizeType,
			count: count ? count : 1,
			success: (res) => {
				resolve(res.tempFilePaths)
			},
			fail(e) {
				reject(e)
			}
		})
	})
};
//上传图片
const addimg = (imgfil) => {
	console.log(imgfil, '上传的文件路径')
	return new Promise((resolve, reject) => {
		var that = this;
		uni.uploadFile({ //该上传仅为示例,可根据自己业务修改或封装,注意:统一上传可能会导致服务器压力过大
			url: baseUrls + '/api/common/upload',
			file: '', //有files数组时,会忽略filePath和name
			filePath: imgfil,
			name: 'file',
			// enctype: "multipart/form-data",
			formData: { //后台以post方式接收
				'token': uni.getStorageSync('token'), //自己系统中的用户id
			},
			success: (uploadFileRes) => {
				console.log(uploadFileRes);
				resolve(JSON.parse(uploadFileRes.data).data.url)
				// uni.hideLoading()
			},
			fail: (e) => {
				// this.$api.msg('图片上传失败')
				reject(e)
			}
		});
	})
}

export default {
	Getajax,
	uploadImg
}
